import sqlite3

class ShopTable:
    def __init__(self, db_path='shop_table.db'):
        self.conn = sqlite3.connect(db_path)
        self.cursor = self.conn.cursor()
        self._create_table()

    def _create_table(self):
        self.cursor.execute('''
        CREATE TABLE IF NOT EXISTS shop_table (
            id INTEGER PRIMARY KEY,
            name TEXT NOT NULL,
            specifications TEXT NOT NULL,
            price TEXT,
            position TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
        ''')
        self.conn.commit()

    def insert(self, name, specifications, price, position):
        self.cursor.execute(
            "INSERT INTO shop_table (name, specifications, price, position) VALUES (?, ?, ?, ?)",
            (name, specifications, price, position)
        )
        self.conn.commit()

    def search(self, name, top_n=10):
        query = """
        SELECT name, specifications, price, position 
        FROM shop_table 
        WHERE name LIKE ? 
        ORDER BY created_at DESC 
        LIMIT ?
        """
        self.cursor.execute(query, (f"%{name}%", top_n))
        return self.cursor.fetchall()

    def close(self):
        self.conn.close()